<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    /**
     * 会员列表
     */
    public function lists() {
        $M_user = M('user');

        $p_user = I('get.user');
        $p_op = I('get.op', '1', 'intval');
        
        $user_where['cateid'] = array('eq', $p_op);
        if($p_user) {
            $user_where['phone'] = array('like', "%$p_user%");
        }
        
        $count = $M_user->where($user_where)->count();
        
        $Page = new \Think\Page($count, 15);
        //定制分页类
        $Page->setConfig('header','<span class="sabrosus">共 %TOTAL_ROW% 条记录</span>'); //显示内容
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','首页');
        $Page->setConfig('last','末页');
        $Page->setConfig('theme'," %HEADER% %FIRST% %UP_PAGE%  %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page -> show();
        
        
        $users = $M_user->where($user_where)->order('id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $M_recommend = M('recommend');
        $M_salesman = M('salesman');
        
        foreach ($users as $k=>$v) {
            $rec_row = $M_recommend->where(array('typeid'=>$p_op, 'uid'=>$v['id']))->field('cateid, opid')->find();
            if ($rec_row) {
                if ($rec_row['cateid']==1) {
                    $users[$k]['rec_type'] = '会员';
                    $users[$k]['rec_user'] = $M_user->where(array('id'=>$rec_row['opid']))->field('phone as rec_phone, nickname as rec_name')->find();
                } else if ($rec_row['cateid']==2) {
                    $users[$k]['rec_type'] = '医生';
                    $users[$k]['rec_user'] = $M_user->where(array('id'=>$rec_row['opid']))->field('phone as rec_phone, nickname as rec_name')->find();
                } else if ($rec_row['cateid']==3) {
                    $users[$k]['rec_type'] = '业务员';
                    $users[$k]['rec_user'] = $M_salesman->where(array('id'=>$rec_row['opid']))->field('phone as rec_phone, nickname as rec_name')->find();
                }
            }
        }
        
        $this->lists = $users;
        $this->op = $p_op;
        $this->page = $show;
        
        $this->display();
    }
    
    /**
     * 会员详情
     */
    public function detail($id=0) {
        $M_user = M('user');
        $user = $M_user->find($id);
        
        $M_corn = M('corn');
        $user['corn'] = $M_corn->where('cateid=1 AND uid='.$id)->getField('corn');
        
        $this->user = $user;
        $this->display();
    }
    
    /**
     * 添加会员
     */
    public function add() {
        if(IS_POST) {
            $p_nick = I('post.nickname');
            $p_user = I('post.username');
            $p_pass = I('post.password');
            $p_email = I('post.email');
            $p_domain_arr = I('post.domain');
            
            $M_user = M('user');
            $M_domain = M('domain');
            
            $user_data['nickname'] = $p_nick;
            $user_data['username'] = $p_user;
            $user_data['password'] = md5($p_pass);
            $user_data['email'] = $p_email;
            
            $userid = $M_user->add($user_data);
            if(!$userid) {
                $this->error("添加失败");
            }
            
            $domain_data = array();
            foreach ($p_domain_arr as $p_domain_item) {
                if($p_domain_item){
                    $domain_data[] = array('userid'=> $userid,'domain'=>$p_domain_item, 'addtime'=>date('Y-m-d H:i:s'));
                }
            }
            $domain_add = $M_domain->addAll($domain_data);
            if(!$domain_add) {
                $this->error("域添加失败");
            }
            $this->success("添加成功" , U('lists'));
        } else {
            $this->display();
        }
    }
    
    /**
     * 修改会员
     */
    public function mod() {
        if(IS_POST) {
            $p_password = I('post.password');
            $p_id = I('post.id');
            
            if (!$p_password OR !$p_id) $this->error('数据提交异常！');
            
            $M_user = M('user');
            $saved = $M_user->where(array('id'=>$p_id))->save(array('password'=>md5($p_password)));
            
            if(!$saved) {
                $this->error("修改失败！");
            } else {
                $this->success('修改成功!');
            }
            
        } else {
            $userid = I('get.id');
            $user = $this->getUser($userid);
            if(!$user) {
                $this->error('数据异常或用户不存在!');
            }
            
            $this->user = $user;
            $this->display();
        }
    }
    
    /**
     * 删除会员
     */
    public function del($id=0) {
        $user = $this->getUser($id);
        if(!$user){
            $this->error('数据异常或用户不存在!');
        }
        
        $M_user = M('user');
        $deled = $M_user->delete($id);
        if($deled) {
            // 删除推荐记录
            $M_recommend = M('recommend');
            $M_recommend->where(array('uid'=>$id))->delete();
            
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    
    /**
     * 删除会员
     */
    public function delall() {
        $p_opid = I('post.opid');
        
        $M_user = M('user');
        $M_recommend = M('recommend');
        
        foreach ($p_opid as $k=>$v) {
            $deled[] = $M_user->delete($v);
            
            // 删除推荐记录
            $M_recommend->where(array('uid'=>$v))->delete();
        }
        
        if($deled) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    
    /**
     * 获取会员信息
     */
    private function getUser($userid=0) {
        $M_user = M('user');
        
        if(!$userid) {
            return false;
        }
        
        $user = $M_user->find($userid);
        if(!$user) {
            return false;
        }
        
        return $user;
    }
    
    /**
     * 医生列表
     */
    public function doclists() {
        $M_doctor = M('doctor');

        $where['phone'] = array('LIKE','%%');
        $p_user = I('get.user');

        if($p_user) {
            $user_where['phone'] = array('like', "%$p_user%");
        }
        
        $count = $M_doctor->where($user_where)->count();
        
        $Page = new \Think\Page($count, 15);
        //定制分页类
        $Page->setConfig('header','<span class="sabrosus">共 %TOTAL_ROW% 条记录</span>'); //显示内容
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $Page->setConfig('first','首页');
        $Page->setConfig('last','末页');
        $Page->setConfig('theme'," %HEADER% %FIRST% %UP_PAGE%  %LINK_PAGE% %DOWN_PAGE% %END%");
        $show = $Page -> show();
        
        
        $doctors = $M_doctor->where($user_where)->order('id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->lists = $doctors;
        $this->page = $show;
        
        $this->display();
    }
    
    /**
     * 导出信息
     */
    public function export($typeid=1) {
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        
        require_once LIB_PATH. 'Org/Util/PHPExcel.class.php';
        
        $objPHPExcel = new \PHPExcel();
        
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("PHPExcel Test Document")
        ->setSubject("PHPExcel Test Document")
        ->setDescription("Test document for PHPExcel, generated using PHP classes.")
        ->setKeywords("office PHPExcel php")
        ->setCategory("Test result file");
        
        // 设置标题
        
        if ($typeid==1) {
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '编号')
            ->setCellValue('B1', '手机号')
            ->setCellValue('C1', '名称')
            ->setCellValue('D1', '性别')
            ->setCellValue('E1', '职业')
            ->setCellValue('F1', '所在城市')
            ->setCellValue('G1', '关注过敏类型')
            ->setCellValue('H1', '注册时间')
            ->setCellValue('I1', '是否微信授权');
        } else {
            // 医生
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '编号')
            ->setCellValue('B1', '手机号')
            ->setCellValue('C1', '名称')
            ->setCellValue('D1', '性别')
            ->setCellValue('E1', '职业')
            ->setCellValue('F1', '所在城市')
            ->setCellValue('G1', '注册时间')
            ->setCellValue('H1', '是否微信授权');
        }
        
        
        // 筛选用户信息
        $M_user = M('user');
        $user_rows = $M_user->where(array('cateid'=>$typeid))->order('addtime DESC')->select();
        
        $sex = array('', '男', '女');
        
        $i = 1;
        $wx = '否';
        foreach ($user_rows as $user_k=>$user_v) {
            $i++;
            
            if ($user_v['openid']) {
                $wx = '是';
            }
            
            if ($typeid==1) {
                $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$i, $user_k+1)
                ->setCellValueExplicit('B'.$i, $user_v['phone'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$i, $user_v['nickname'])
                ->setCellValue('D'.$i, $sex[$user_v['sex']])
                ->setCellValue('E'.$i, $user_v['jobs'])
                ->setCellValue('F'.$i, $user_v['city'])
                ->setCellValue('G'.$i, $user_v['qa'])
                ->setCellValue('H'.$i, $user_v['addtime'])
                ->setCellValue('I'.$i, $wx);
            } else {
                // 医生
                $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$i, $user_k+1)
                ->setCellValueExplicit('B'.$i, $user_v['phone'], \PHPExcel_Cell_DataType::TYPE_STRING)
                ->setCellValue('C'.$i, $user_v['nickname'])
                ->setCellValue('D'.$i, $sex[$user_v['sex']])
                ->setCellValue('E'.$i, $user_v['jobs'])
                ->setCellValue('F'.$i, $user_v['city'])
                ->setCellValue('G'.$i, $user_v['addtime'])
                ->setCellValue('H'.$i, $wx);
            }
        }
        
        //$objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
        //$objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
        //$objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
        
        // Rename worksheet
        if ($typeid==1) {
            $objPHPExcel->getActiveSheet()->setTitle('用户信息导出');
        } else {
            $objPHPExcel->getActiveSheet()->setTitle('医生信息导出');
        }
        
        
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);
        
        /*$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save(str_replace('.php', '.xlsx', __FILE__));*/
        
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.date('Y-m-d_').rand(1000, 9999).'.xlsx"');
        header('Cache-Control: max-age=0');
        
        $objWriter = \PHPExcel_IOFactory:: createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save( 'php://output');
    }
}